<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2017 河源市卓锐科技有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------

namespace app\goods\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use think\Cache;
use think\Db;
use app\goods\model\GoodsType as GoodsTypeModel;
use app\goods\model\Attr as AttrModel;
use app\goods\model\GoodsClass as GoodsClassModel;

/**
 * 商品分类
 * @package app\admin\controller
 */
class Goodstype extends Admin
{
    /**
    *商品分类
    */


    public function index(){
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        $order = $this->getOrder('sort ASC,typeid DESC');
        $data_list = GoodsTypeModel::order($order)->select();
        foreach ($data_list as $key => $value) {
            $data_list[$key]['number'] = GoodsClassModel::where('typeid', $value['typeid'])->count();
        }       
        
        $this->assign('page_title', '分类列表');
        $this->assign('menus', $this->getNestMenu($data_list));
        return $this->fetch();
    }


    /**
    *新增
    */
    public function add(){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if(empty($data['classname'])){
                $this->error('请填写名称');
            }
            $result = GoodsTypeModel::add($data);
            if($result) {
                $this->success('新增成功');
            }else{
                $this->error('新增失败');
            }
        }

        //顶级分类列表
        $data_list = GoodsTypeModel::where(array('status' => '1', 'parentid' => '0'))->order('sort')->column('typeid,classname');

        //默认分类
        $pid = input('pid');

        return ZBuilder::make('form')
        ->addFormItems([ // 批量添加列
            ['select','parentid','上级分类','<span>默认顶级分类</span>',$data_list,$pid],            
            ['text', 'classname', '名称', '必填'],
            ['text', 'sort', '排序'],
            ['image', 'thumb', '图片'],
            ['radio', 'status' , '状态', '', ['0' => '禁用' ,'1' => '启用'], '1'],
            ['radio', 'show' , '前台展示', '', ['0' => '不展示' ,'1' => '展示'], '1'],
        ])
        ->layout(['classname' => 6, 'status' => 6, 'sort' => 6, 'thumb' => 6, 'parentid' => 6, 'show' => 6])
        ->fetch();
    }

    /**
    *修改
    */
    public function edit($id = 0){
        if ($id === 0) return $this->error('缺少参数');

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if(empty($data['classname'])){
                $this->error('请填写名称');
            }
            $result = GoodsTypeModel::update($data);
            if($result) {
                $res = db('goods_class')->where('typeid', $data['typeid'])->update(['parentid' => $data['parentid']]);
                $this->success('修改成功', cookie('__forward__'));
            }else{
                $this->error('修改失败');
            }
        }

        //详情
        $info      = GoodsTypeModel::find($id);

        //顶级分类列表
        $data_list = GoodsTypeModel::where(array('status' => '1', 'parentid' => '0'))->order('sort')->column('typeid,classname');


        return ZBuilder::make('form')
        ->addFormItems([ // 批量添加列
            ['hidden', 'typeid'],
            ['select','parentid','上级分类','<span>默认顶级分类</span>',$data_list],            
            ['text', 'classname', '名称', '必填'],
            ['text', 'sort', '排序'],
            ['image', 'thumb', '图片'],
            ['radio', 'status' , '状态', '', ['0' => '禁用' ,'1' => '启用'], '1'],
            ['radio', 'show' , '前台展示', '', ['0' => '不展示' ,'1' => '展示'], '1'],          
        ])
        ->setFormData($info)
        ->layout(['classname' => 6, 'status' => 6, 'sort' => 6, 'thumb' => 6, 'parentid' => 6, 'show' => 6])
        ->fetch();
    }

    /**
    *属性列表
    */
    public function attr($id = 0){

        if($this->request->isPost()){
            $data = $this->request->post();
            if(!empty($data['attrid'])){
                $data['attrid'] = ','.implode(',', $data['attrid']).',';
            }
            $result = GoodsTypeModel::update($data);
            if($result){
                $this->success('修改成功', cookie('__forward__'));
            }else{
                $this->error('修改失败');
            }
        }

        if($id == 0){
            $this->error('缺少参数');
        }

        //所有启用属性
        $attr_list = AttrModel::where('status','1')->select();

        //单选
        $radio        = [];
        $radioarr1    = [];
        $radioarr2    = [];
        //多选
        $checkbox     = [];
        $checkboxarr1 = [];
        $checkboxarr2 = [];
        //文本
        $text         = [];
        $textarr1     = [];
        $textarr2     = [];
        //下拉
        $select       = [];
        $selectarr1   = [];
        $selectarr2   = [];
        //图片
        $image        = [];
        $imagearr1    = [];
        $imagearr2    = [];
        foreach ($attr_list as $key => $value) {
            switch ($value['inittype']) {
                case '1':
                    $textarr1[] = $value['attrid'];
                    $textarr2[] = $value['attrname'];
                    break;
                case '2':
                    $imagearr1[] = $value['attrid'];
                    $imagearr2[] = $value['attrname'];
                    break;
                case '3':
                    $selectarr1[] = $value['attrid'];
                    $selectarr2[] = $value['attrname'];
                    break;
                case '4':
                    $radioarr1[] = $value['attrid'];
                    $radioarr2[] = $value['attrname'];
                    break;
                case '5':
                    $checkboxarr1[] = $value['attrid'];
                    $checkboxarr2[] = $value['attrname'];
                    break;
                
            }
        }
        $text     = array_combine($textarr1,$textarr2);
        $image    = array_combine($imagearr1,$imagearr2);
        $select   = array_combine($selectarr1,$selectarr2);
        $radio    = array_combine($radioarr1,$radioarr2);
        $checkbox = array_combine($checkboxarr1,$checkboxarr2);
        

        //详情
        $info = GoodsTypeModel::where('typeid',$id)->find();

        return ZBuilder::make('form')
        ->addFormItems([ // 批量添加列
            ['hidden', 'typeid', $info['typeid']],
            ['checkbox','attrid','文本录入','',$text, $info['attrid']],
            ['checkbox','attrid','图片录入','',$image, $info['attrid']], 
            ['checkbox','attrid','下拉录入','',$select, $info['attrid']], 
            ['checkbox','attrid','单选录入','',$radio, $info['attrid']], 
            ['checkbox','attrid','多选录入','',$checkbox, $info['attrid']],      
        ])
        /*->setFormData($info)*/
        ->fetch();

    }


   




    /**
    *模板
    */
    private function getNestMenu($lists = [], $max_level = 0, $pid = 0, $curr_level = 1)
    {
        $result = '';
        foreach ($lists as $key => $value) {
            if ($value['parentid'] == $pid) {
                $disable  = $value['status'] == 0 ? 'dd-disable' : '';

                // 组合节点
                $result .= '<li class="dd-item dd3-item '.$disable.'" data-id="'.$value['typeid'].'">';
                $result .= '<div class="dd-handle dd3-handle">拖拽</div><div class="dd3-content">'.$value['classname'];
                if($value['show'] == 1){
                    $result .= '<a href="javascript:void(0);"  data-toggle="tooltip" data-original-title="前台展示" ><i class="fa fa-check-circle-o fa-fw"></i></a>';
                }
                if($pid != 0){
                    $result.='('.$value['number'].')';
                }
                /*if ($value['url_value'] != '') {
                    $result .= '<span class="link"><i class="fa fa-link"></i> '.$value['url_value'].'</span>';
                }*/

                //$result .= ' <span style="margin-left:30px;">排序：'.$value['sort'].'<span>';
                
                $result .= '<div class="action">';
                if($pid == 0){
                    $result .= '<a href="'.url('add', [ 'pid' => $value['typeid']]).'" data-toggle="tooltip" data-original-title="新增子节点"><i class="list-icon fa fa-plus fa-fw"></i></a>';
                }else{
                    $result .= '<a href="'.url('change', [ 'id' => $value['typeid']]).'" data-toggle="tooltip" data-original-title="转移"><i class="list-icon fa fa-fw fa-arrows"></i></a>';
                    //$result .= '<a href="'.url('attr', ['id' => $value['typeid']]).'" data-toggle="tooltip" data-original-title="属性"><i class="list-icon fa fa-fw fa-cogs"></i></a>';
                }

                $result .= '<a href="'.url('edit', ['id' => $value['typeid']]).'" data-toggle="tooltip" data-original-title="编辑"><i class="list-icon fa fa-pencil fa-fw"></i></a>';
                if ($value['status'] == 0) {
                    // 启用
                    $result .= '<a href="javascript:void(0);" data-ids="'.$value['typeid'].'" class="enable" data-toggle="tooltip" data-original-title="启用"><i class="list-icon fa fa-check-circle-o fa-fw"></i></a>';
                } else {
                    // 禁用
                    $result .= '<a href="javascript:void(0);" data-ids="'.$value['typeid'].'" class="disable" data-toggle="tooltip" data-original-title="禁用"><i class="list-icon fa fa-ban fa-fw"></i></a>';
                }
                $result .= '<a href="'.url('delete', ['id' => $value['typeid'], 'table' => 'admin_menu']).'" data-toggle="tooltip" data-original-title="删除" class="ajax-get confirm"><i class="list-icon fa fa-times fa-fw"></i></a></div>';

                $result .= '</div>';


                if ($max_level == 0 || $curr_level != $max_level) {
                    unset($lists[$key]);
                    // 下级节点
                    $children = $this->getNestMenu($lists, $max_level, $value['typeid'], $curr_level + 1);
                    if ($children != '') {
                        $result .= '<ol class="dd-list">'.$children.'</ol>';
                    }
                }

                $result .= '</li>';
            }
        }
        return $result;
    }


    /**
    *启用
    */
     public function enable($record = []){
        $data   = $this->request->post();
        $result = GoodsTypeModel::where(array('typeid' => $data['ids']))->setField('status', '1');
        if($result){
            $data['code'] = '修改成功';
        }else{
            $data['msg']  = '无修改';
        }

        return $data;
    }

    /**
     * 禁用
     */
    public function disable($record = []){
        $data   = $this->request->post();
        $result = GoodsTypeModel::where(array('typeid' => $data['ids']))->setField('status', '0');
        if($result){
            $data['code'] = '修改成功';
        }else{
            $data['msg']  = '无修改';
        }

        return $data;
    }

    /**
    *删除
    */
    public function delete($record = []){
        $data   = input('');
        $info   = GoodsTypeModel::where('typeid', $data['id'])->find();
        if($info['parentid'] == 0){
            $child = GoodsTypeModel::where('parentid',$data['id'])->count();
            if($child > 0){
                $this->error('该分类下含有子类,不能删除');
            }
        }else{
            $class = GoodsClassModel::where('typeid',$data['id'])->count();
            if($class > 0){
                $this->error('该分类下面含有款类,不能删除');
            }
        }
        $result = GoodsTypeModel::where(array('typeid' => $data['id']))->delete();
        if($result){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }

    /**
    *转移款类
    */
    public function change($id = 0){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if(empty($data['typeid'])){
                $this->error('必须选择转移分类');
            }
            if($data['id'] == $data['typeid']){
                $this->error('转移分类不能与分类一致');
            }
            $result = GoodsClassModel::where('typeid',$data['id'])->update(array('typeid'=>$data['typeid']));
            if($result) {
                $this->success('转移成功', cookie('__forward__'));
            }else{
                $this->error('转移失败');
            }
        }

        //详情
        $info = GoodsTypeModel::where('typeid', $id)->find();


        //顶级分类列表
        $top_list  = GoodsTypeModel::where(array('status' => '1', 'parentid' => '0'))->column('typeid,classname');

        $type_list = GoodsTypeModel::where('parentid', $info['parentid'])->column('typeid,classname');

        return ZBuilder::make('form')
        ->addFormItems([ // 批量添加列
            ['hidden', 'id', $id],            
            ['linkage', 'parentid', '顶级分类', '', $top_list, '', url('get_type'),'typeid'],
            ['select', 'typeid', '转移分类', '',$type_list], 
            
        ])
        ->setFormData($info)
        ->layout(['parentid' => 6, 'typeid' => 6])
        ->fetch();
    }

    /**
    *获取子类type
    */
    public function get_type(){
        $id = input('parentid');
        $data = GoodsTypeModel::where(array('status' => '1','parentid' => $id))->column('typeid,classname');
        $list = [];
        foreach ($data as $key => $value) {
            $list[]=['key' => $key, 'value' => $value];
        }
        $data_list['list'] = $list;
        $data_list['code'] = '1'; //判断状态
        $data_list['msg']  = '请求成功'; //回传信息
        return json($data_list);
    }

   
}
